package com.ruoyi.api.user;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.api.util.DateUtil;
import com.ruoyi.api.util.DistanceUtils;
import com.ruoyi.api.util.GPSUtil;
import com.ruoyi.api.util.JPushUtil;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.user.domain.Audio;
import com.ruoyi.user.domain.Battery;
import com.ruoyi.user.domain.Health;
import com.ruoyi.user.domain.HealthRate;
import com.ruoyi.user.domain.Location;
import com.ruoyi.user.domain.LocationSet;
import com.ruoyi.user.domain.Message;
import com.ruoyi.user.domain.Sleep;
import com.ruoyi.user.domain.Step;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.domain.UserMachine;
import com.ruoyi.user.domain.Warning;
import com.ruoyi.user.service.IAudioService;
import com.ruoyi.user.service.IBatteryService;
import com.ruoyi.user.service.IHealthRateService;
import com.ruoyi.user.service.IHealthService;
import com.ruoyi.user.service.ILocationService;
import com.ruoyi.user.service.ILocationSetService;
import com.ruoyi.user.service.IMachineService;
import com.ruoyi.user.service.IMessageService;
import com.ruoyi.user.service.ISleepService;
import com.ruoyi.user.service.IStepService;
import com.ruoyi.user.service.IUserMachineService;
import com.ruoyi.user.service.IUserService;
import com.ruoyi.user.service.IWarningService;

import io.swagger.annotations.ApiOperation;

/**
 * APP用户 信息操作处理
 * 
 * @author ruoyi
 * @date 2018-12-14
 */
@Controller
@RequestMapping("/api/third")
public class ApiThirdDataController extends BaseController
{
	
	private static final Logger log = LoggerFactory.getLogger(ApiThirdDataController.class);
	
    private String prefix = "api:third";
	
    @Autowired
	private ILocationService locationService;	
    @Autowired
	private IWarningService warningService;
    @Autowired
	private IHealthService healthService;
    @Autowired
	private IHealthRateService healthRateService;
    @Autowired
	private IStepService stepService;
    @Autowired
	private IAudioService audioService;
    @Autowired
	private ILocationSetService locationSetService;
    @Autowired
	private IUserMachineService userMachineService;
    @Autowired
	private IUserService userService;
    @Autowired
	private IMessageService messageService;
    @Autowired
	private IMachineService machineService;
    @Autowired
	private ISleepService sleepService;
    @Autowired
    private IBatteryService batteryService;
	
	/**
	 * 4.1 定位数据
	 * @return
	 */
	@PostMapping("/location")
	@ResponseBody
	@ApiOperation(value="定位数据", notes="定位数据",produces = "application/json")
	public AjaxResult location(@RequestBody Location location)
	{
		if(location!=null&&location.getImei()!=null){
			location.setCreateTime(new Date());
			location.setLocateType(0);
			locationService.insertLocation(location);
			try {
				LocationSet param = new LocationSet();
				param.setImei(location.getImei());
				List<LocationSet> list = locationSetService.selectLocationSetList(param);
				if(list!=null&&list.size()>0){
					LocationSet now = list.get(0);
					//boolean flag = GPSUtil.isInSiteRange(location.getLat(), location.getLon(), now.getLat(), now.getLon(), now.getRadius());
					boolean flag = DistanceUtils.isInSiteRange(location.getLat(), location.getLon(), now.getLat(), now.getLon(), now.getRadius());
					if(!flag){//超出范围
						System.out.println("设备["+location.getImei()+"]定位["+location.getLon()+","+location.getLat()+"]超出电子围栏");
						UserMachine paramUM = new UserMachine();
						paramUM.setMCode(location.getImei());
						paramUM.setStatus(1);
						List<UserMachine> listu = userMachineService.selectUserMachineList(paramUM);
						if(listu!=null&&listu.size()>0){
							String phoneSend = "";
							int i = 0;
							String ids = "";
							for(UserMachine c:listu){
								User u = userService.selectUserById(c.getUId());
								if(i==0){
									ids += c.getUId();
									if(u.getPhone()!=null&&!"".equals(u.getPhone())){
										phoneSend += u.getPhone();
									}
								}else{
									ids += ","+c.getUId();
									if(u.getPhone()!=null&&!"".equals(u.getPhone())){
										phoneSend += ","+u.getPhone();
									}
								}
								i++;
							}
							try {
								HttpUtils.sendGet("https://api.zhuanxinyun.com/api/v2/sendSms.json", "appKey=WSaQfW3hjbksh37phGyM7vBD8dRkNFNA&appSecret=12cd794f36ed54a60f6ac9e37a4cb0646901&phones="+phoneSend+"&content=【安普尔】你的设备["+location.getImei()+"]定位超出电子围栏，请留意");
								Map<String, String> parm = new HashMap<String, String>();
								//这里的id是,移动端集成极光并登陆后,极光用户的rid
								parm.put("id", ids);
								//设置提示信息,内容是文章标题
								parm.put("msg","【安普尔】你的设备["+location.getImei()+"]定位超出电子围栏，当前坐标为["+location.getLon()+","+location.getLat()+"]，请留意");
								JPushUtil.jpushAll(parm);
							} catch (Exception e) {
								e.printStackTrace();
							}
							
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return success();
		}else{
			return error("thd-0001","定位数据异常");
		}
	}
	
	/**
	 * 4.2预警数据
	 * @return
	 */
	@PostMapping("/warning")
	@ResponseBody
	@ApiOperation(value="预警数据", notes="预警数据",produces = "application/json")
	public AjaxResult warning(@RequestBody Warning warning)
	{
		if(warning!=null&&warning.getImei()!=null){
			warning.setCreateTime(new Date());
			warningService.insertWarning(warning);
			try {
				if(warning.getWarningType()==1){
					Message msg = new Message();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
					msg.setContent("小安提示：您关注的【"+warning.getImei()+"】在"+sdf.format(warning.getCreateTime())+"发出SOS紧急呼救，请予以关注！");
					msg.setCreateTime(new Date());
					msg.setType(2);
					msg.setImei(warning.getImei());
					messageService.insertMessage(msg);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return success();
		}else{
			return error("thd-0002","预警数据异常");
		}
	}
	
	/**
	 * 4.3心率血压数据
	 * @return
	 */
	@PostMapping("/health")
	@ResponseBody
	@ApiOperation(value="心率血压数据", notes="心率血压数据",produces = "application/json")
	public AjaxResult health(@RequestBody Health health)
	{
		if(health!=null&&health.getImei()!=null){
			health.setCreateTime(new Date());
			healthService.insertHealth(health);
			HealthRate healthRate = new HealthRate();
			healthRate.setCreateTime(new Date());
			healthRate.setHeartRate(health.getHeartRate());
			healthRate.setImei(health.getImei());
			/*health.setUpdateBy(requestVo.getDateTime());*/
			healthRateService.insertHealth(healthRate);
			try {
				if(health.getHeartRate().intValue()<60||health.getHeartRate().intValue()>110){//心率低于60，高于110，就为异常
					Message msg = new Message();
					msg.setContent("小安提示：您关注的【"+health.getImei()+"】当前心率数据不稳定，请您关注安+APP查看健康数据，如有需要请在线咨询“我的医生”。祝您健康！");
					msg.setCreateTime(new Date());
					msg.setType(1);
					msg.setImei(health.getImei());
					messageService.insertMessage(msg);
				}
				if(health.getSdp().intValue()>150||health.getDbp().intValue()<60){//血压  舒张压低于60  收缩压高于150就为异常
					Message msg = new Message();
					msg.setContent("小安提示：您关注的【"+health.getImei()+"】血压数据异常波动，详情请查看安+APP健康数据。如有需要，请：1.使用专业的血压计测量；2.测量前30 min内无剧烈运动、吸烟、情绪变化等影响血压的因素，情绪稳定，袖口不宜过紧。祝您健康！");
					msg.setCreateTime(new Date());
					msg.setType(1);
					msg.setImei(health.getImei());
					messageService.insertMessage(msg);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return success();
		}else{
			return error("thd-0003","心率血压数据异常");
		}
	}
	
	/**
	 * 4.4电量/计步数据
	 * @return
	 */
	@PostMapping("/beatHeart")
	@ResponseBody
	@ApiOperation(value="电量/计步数据", notes="电量/计步数据",produces = "application/json")
	public AjaxResult beatHeart(@RequestBody Step step)
	{
		if(step!=null&&step.getImei()!=null){
			Date date = new Date();
			step.setCreateTime(date);
			try {
				int hour = DateUtil.getHour(date);
				if(hour>=21||hour<7){//晚上9:00-早上7点
					Step paramStep = new Step();
					paramStep.setImei(step.getImei());
					Step stepOld = stepService.selectNewStep(paramStep);
				    int now = step.getPedometer().intValue();
				    int old = stepOld.getPedometer().intValue();
				    int minutes = DateUtil.diffMinutes(stepOld.getCreateTime(),date);
				    int type = 3;//默认清醒
				    if((now-old)>10){
				    	type = 3;
				    }else if((now-old)>3){//浅睡
				    	type = 2;
				    }else{//熟睡
				    	type = 1;
				    }
				    if((hour>=23||hour<5)&&type==3){//熬夜
						type = 4;
					}
					step.setType(type);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					Sleep param = new Sleep();
					param.setImei(step.getImei());
					if(hour<7){
						//param.setSleepDate(sdf.parse(DateUtil.beforeDaysToNowDate(1, "yyyy-MM-dd")));//获取明天的日期
						param.setUpdateBy(DateUtil.beforeDaysToNowDate(1, "yyyy-MM-dd"));//SleepDate借用updateBy字段
					}else{
						/*param.setSleepDate(sdf.parse(sdf.format(new Date())));*/
						param.setUpdateBy(sdf.format(date));//SleepDate借用updateBy字段
					}
					List<Sleep> list = sleepService.selectSleepList(param);
					if(list!=null&&list.size()>0){
						Sleep sleep = list.get(0);
						if(type==1){
							sleep.setDeepCount(sleep.getDeepCount()+minutes);
						}else if(type==2){
							sleep.setEasyCount(sleep.getEasyCount()+minutes);
						}else if(type==4){
							sleep.setLateCount(sleep.getLateCount()+minutes);
						}else{
							sleep.setWakeCount(sleep.getWakeCount()+minutes);
						}
						sleepService.updateSleep(sleep);
					}else{
						Sleep sleep = new Sleep();
						if(type==1){
							sleep.setDeepCount(minutes);
						}else if(type==2){
							sleep.setEasyCount(minutes);
						}else if(type==4){
							sleep.setLateCount(minutes);
						}else{
							sleep.setWakeCount(minutes);
						}
						sleep.setImei(step.getImei());
						if(hour>=21){
							sleep.setSleepDate(sdf.parse(sdf.format(new Date())));
						}else{
							sleep.setSleepDate(sdf.parse(DateUtil.beforeDaysToNowDate(1, "yyyy-MM-dd")));//获取昨天的日期
						}
						sleep.setCreateTime(date);
						sleepService.insertSleep(sleep);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			stepService.insertStep(step);
			Battery bb = new Battery();
			bb.setBattery(step.getBattery());
			bb.setImei(step.getImei());
			bb.setCreateTime(new Date());
			batteryService.insertBattery(bb);
			return success();
		}else{
			return error("thd-0004","电量/计步数据异常");
		}
	}
	
	/**
	 * 4.5语音数据
	 * @return
	 */
	@PostMapping("/audio")
	@ResponseBody
	@ApiOperation(value="语音数据", notes="语音数据",produces = "application/json")
	public AjaxResult audio(@RequestBody Audio audio)
	{
		if(audio!=null&&audio.getImei()!=null){
			audio.setCreateTime(new Date());
			audioService.insertAudio(audio);
			return success();
		}else{
			return error("thd-0005","语音数据异常");
		}
	}
	
}
